import React, { useState, useCallback } from 'react';
import { StyleSheet, TextInput } from 'react-native';

import Entypo from 'react-native-vector-icons/Entypo';

import Text from './Text';
import Block from './Block';
import Button from './Button';
import { theme } from '../../constants';

export default function Input(props) {
  const [toggleSecure, setToggleSecure] = useState(false);

  // with state
  const renderToggle = useCallback(() => {
    const { secure, rightLabel } = props;
    if (!secure) return null;
    return (
      <Button
        style={styles.toggle}
        onPress={() => setToggleSecure(!toggleSecure)}
      >
        {rightLabel || (
          <Entypo
            name={!toggleSecure ? 'eye-with-line' : 'eye'}
            size={theme.sizes.font * 1.35}
            style={{ color: theme.colors.gray }}
          />
        )}
      </Button>
    );
  }, [props, toggleSecure]);

  const {
    email, phone, number, secure, error, style, ...restProps
  } = props;

  const isSecure = toggleSecure ? false : secure;

  const inputStyles = [
    styles.input,
    error && { borderColor: theme.colors.accent },
    style,
  ];

  const inputType = email
    ? 'email-address'
    : number
      ? 'numeric'
      : phone
        ? 'phone-pad'
        : 'default';

  return (
    <Block flex={false} margin={[theme.sizes.base, 0]}>
      {renderLabel(props)}
      <TextInput
        style={inputStyles}
        secureTextEntry={isSecure}
        autoComplete="off"
        autoCapitalize="none"
        autoCorrect={false}
        keyboardType={inputType}
        {...restProps}
      />
      {renderToggle()}
      {renderRight(props)}
    </Block>
  );
}

const renderLabel = ({ label, error }) => (
  <Block flex={false}>
    {label ? (
      <Text gray2={!error} accent={error}>
        {label}
      </Text>
    ) : null}
  </Block>
);

const renderRight = ({ rightLabel, rightStyle, onRightPress }) => {
  if (!rightLabel) return null;
  return (
    <Button
      style={[styles.toggle, rightStyle]}
      onPress={() => onRightPress && onRightPress()}
    >
      {rightLabel}
    </Button>
  );
};

const styles = StyleSheet.create({
  input: {
    borderWidth: StyleSheet.hairlineWidth,
    borderColor: theme.colors.black,
    borderRadius: theme.sizes.radius,
    fontSize: theme.sizes.font,
    fontWeight: '500',
    color: theme.colors.black,
    height: theme.sizes.base * 3,
  },
  toggle: {
    position: 'absolute',
    alignItems: 'flex-end',
    width: theme.sizes.base * 2,
    height: theme.sizes.base * 2,
    top: theme.sizes.base,
    right: 0,
  },
});
